package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.StockBackMapper;
import com.qingcheng.pojo.goods.StockBack;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.StockBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 回滚订单方法
 */
@Service(interfaceClass = StockBackService.class)
public class StockBackServiceImpl implements StockBackService{

    @Autowired
    private StockBackMapper stockBackMapper;

    @Transactional
    public void addList(List<OrderItem> orderItemList) {
        for (OrderItem orderItem : orderItemList) {
            StockBack skuBack =new StockBack();
            skuBack.setOrderId(orderItem.getOrderId());
            skuBack.setSkuId(orderItem.getSkuId());
            skuBack.setNum(orderItem.getNum());
            skuBack.setCreateTime(new Date());
            skuBack.setStatus("0");  //回滚状态 未回滚 0  已回滚 1
            stockBackMapper.insert(skuBack);
        }
    }


    @Autowired
    private SkuMapper skuMapper;
    /**
     * 执行库存回滚
     */
    @Transactional
    public void doBack(){
        StockBack backStock = new StockBack();
        backStock.setStatus("0"); //未回滚的
        //查询所有状态为"0"的记录
        List<StockBack> backStockList = stockBackMapper.select
                (backStock);
        for (StockBack skuBack : backStockList) {
            //增加库存
            skuMapper.deductStock(skuBack.getSkuId(),-skuBack.getNum
                    ());
            //减少销量
            skuMapper.increaseSaleNum(skuBack.getSkuId(),-
                    skuBack.getNum());
            //设置状态  已回滚
            skuBack.setStatus("1");
            skuBack.setBackTime(new Date());  //回滚时间
            stockBackMapper.updateByPrimaryKey(skuBack);
        }
        System.out.println("库存回滚操作结束！");


    }
}
